package email;

/**This code was taken from the following URL
 * http://www.roseindia.net/java/example/java/swing/login-form-swing.shtml 
 * It is a simple login in prompt for our email client
 *  */


import javax.mail.AuthenticationFailedException;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.Properties;
 
class LoginPrompt extends JFrame
{

private static final long serialVersionUID = 1L;
 JPanel panel;
 JLabel label1,label2;
 JTextField  user, pswd;
 BufferedImage image;
 
 public LoginPrompt(){
	
  label1 = new JLabel();
  label1.setText("Username: ");
  user = new JTextField(15);

  label2 = new JLabel();
  label2.setText("Password: ");
  pswd = new JPasswordField(15);
 
  JButton submit=new JButton("Submit");
  submit.setSize(10,10);
  JButton cancel = new JButton("Cancel");
  cancel.setSize(200,100);
  JButton noVis = new JButton();
  JButton newUser = new JButton("Create an Account");
  JButton forgotPass = new JButton("Forgot Password");
 
  panel=new JPanel(new GridLayout(10,4));

  setSize(425,450);
  JPanel logo = new JPanel();
  JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, logo, panel);
  noVis.setVisible(false);
  panel.add(label1);
  panel.add(user);
  panel.add(label2);
  panel.add(pswd);
  panel.add(noVis);
  panel.add(submit);
  panel.add(cancel);
  panel.add(forgotPass);
  panel.add(newUser);
  Dimension minimumSize = new Dimension(400,300);
  logo.setMinimumSize(minimumSize);
  ImageIcon image = new ImageIcon("logo_wBasu.jpg");
  
   JLabel label = new JLabel("", image, JLabel.CENTER);
   label.setSize(minimumSize);
   logo.add(label);
  
  panel.setMinimumSize(minimumSize);
  split.setSize(450, 450);
  split.setDividerLocation(0.5);
  split.setDividerSize(0);
  
  add(split, BorderLayout.CENTER);
  
  //@lance staley
  logo.setBackground(Color.DARK_GRAY);
  panel.setBackground(Color.DARK_GRAY);
  panel.setBorder(BorderFactory.createEtchedBorder(Color.BLACK, Color.BLACK));
  label2.setForeground(Color.WHITE);
  label1.setForeground(Color.WHITE);
  user.setBorder(BorderFactory.createEtchedBorder(Color.LIGHT_GRAY, Color.LIGHT_GRAY));
  pswd.setBorder(BorderFactory.createEtchedBorder(Color.LIGHT_GRAY, Color.LIGHT_GRAY));
  //
  
  pswd.addKeyListener(new KeyListener(){

	@Override
	public void keyPressed(KeyEvent e) {
			 if(e.getKeyChar() == KeyEvent.VK_ENTER){
				String uname = user.getText();
				String pass = pswd.getText();
				if(validLogin(uname,pass) == true){
					setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
					EmailClient2 email = new EmailClient2(uname, pass);
					email.mailSetup();
					EmailClient2.login.dispose();
					setCursor(Cursor.getDefaultCursor());
				}
				else{
					JOptionPane.showMessageDialog(null,"Incorrect username and/or password, try again!");
				}
			 }
	  }

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	 
	
  });
  
  user.addKeyListener(new KeyListener(){

	@Override
	public void keyPressed(KeyEvent e) {
			 if(e.getKeyChar() == KeyEvent.VK_ENTER){
			 String uname = user.getText();
			 String pass = pswd.getText();
			 if(validLogin(uname,pass) == true){
				  	setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
					EmailClient2 email = new EmailClient2(uname, pass);
					email.mailSetup();
					EmailClient2.login.dispose();
					setCursor(Cursor.getDefaultCursor());
				}
				else{
					JOptionPane.showMessageDialog(null,"Incorrect username and/or password, try again!");
				}
			 }
	  }

	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	 
	
  });
  
  submit.addActionListener(new ActionListener(){

	@Override
	public void actionPerformed(ActionEvent e) {
		String uname = user.getText();
		String pass = pswd.getText();
		if(validLogin(uname,pass) == true){
			setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
			EmailClient2 email = new EmailClient2(uname, pass);
			email.mailSetup();
			EmailClient2.login.dispose();
			setCursor(Cursor.getDefaultCursor());
		}
		else{
			JOptionPane.showMessageDialog(null,"Incorrect username and/or password, try again!");
		}
	}
	  
  });
  setTitle("Login");

 
 
 cancel.addActionListener(new ActionListener(){

	@Override
	public void actionPerformed(ActionEvent e) {
		System.exit(0);	
	}
	 
 });


 newUser.addActionListener(new ActionListener(){
	public void actionPerformed(ActionEvent e){
		String url = "https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ltmpl=default";
		openURL(url);
	}
 });
 
 forgotPass.addActionListener(new ActionListener(){
	public void actionPerformed(ActionEvent e){
		String url = "https://www.google.com/accounts/recovery?gaps=AHwGkRnMCjuosfpeH0kkoHibkDdUeIfQ%2F3Q5kbsPStOiMW2LUVZu%2BWdmkp4EmsfQcG8sn8wwcgxtFEI%2F%2BSjmiHV3bwbYS2RVlg%3D%3D&service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F";
		openURL(url);
	}
 });
 }

 
 public boolean validLogin(String username, String password){
	 
	 try{
		 Properties props = new Properties();
			props.setProperty("mail.imap.host", "imap.gmail.com");
			props.setProperty("mail.imap.port", "993");
			props.setProperty("mail.imap.connectiontimeout", "5000");
			props.setProperty("mail.imap.timeout", "5000");
			props.setProperty("mail.imap.socketFactory.class","javax.net.ssl.SSLSocketFactory");
			props.setProperty("mail.imap.socketFactory.fallback", "false");
			props.setProperty("mail.smtp.host", "smtp.gmail.com");
			props.setProperty("mail.smtp.port", "465");
			Session session = Session.getDefaultInstance(props,null);
			Store store = session.getStore("imaps");
			store.connect("imap.gmail.com",username,password);
			store.close();
			return true;
	 }
	 catch(AuthenticationFailedException e){
		 pswd.setText(null);
	 	 user.setText(null);
	 	 user.requestFocusInWindow();
		 return false;
	 }
	 catch(MessagingException e){
		 pswd.setText(null);
		 user.setText(null);
		 user.requestFocusInWindow();
		 return false;
	 }
 }
 
 public static void openURL(String url) {
	 String[] browsers = { "google-chrome", "firefox", "opera",
		      "epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla" };
	 
     try {
        Class<?> d = Class.forName("java.awt.Desktop");
        d.getDeclaredMethod("browse", new Class[] {java.net.URI.class}).invoke(
           d.getDeclaredMethod("getDesktop").invoke(null),
           new Object[] {java.net.URI.create(url)});
        }
     catch (Exception ignore) {
        String osName = System.getProperty("os.name");
        try {
           if (osName.startsWith("Mac OS")) {
              Class.forName("com.apple.eio.FileManager").getDeclaredMethod(
                 "openURL", new Class[] {String.class}).invoke(null,
                 new Object[] {url});
              }
           else if (osName.startsWith("Windows"))
              Runtime.getRuntime().exec(
                 "rundll32 url.dll,FileProtocolHandler " + url);
           else {
              String browser = null;
              for (String b : browsers)
                 if (browser == null && Runtime.getRuntime().exec(new String[]
                       {"which", b}).getInputStream().read() != -1)
                    Runtime.getRuntime().exec(new String[] {browser = b, url});
              if (browser == null)
                 throw new Exception(Arrays.toString(browsers));
              }
           }
        catch (Exception e) {
           JOptionPane.showMessageDialog(null, "Error" + "\n" + e.toString());
           }
        }
     }
 
}

